package com.speaktoitcookbook.dao.impl;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.speaktoitcookbook.bean.DishStep;
import com.speaktoitcookbook.dao.IDishStepDao;
import com.speaktoitcookbook.util.DBUtil;
import com.speaktoitcookbook.util.TransformUtil;

/**
 * 菜谱做法步骤数据操作实现类
 * 
 * @author 赛艳志
 * 
 */
public class DishStepDaoImpl implements IDishStepDao {
    private Connection conn;

    public DishStepDaoImpl(Connection conn) {
        this.conn = conn;
    }

    @Override
    public boolean doCreate(DishStep step) throws SQLException {
        boolean result = false;
        String sql = "insert into `tb_dishstep`(`cbID`, `dsNO`, `dsPic`, `dsContent`) values(?, ?, ?, ?)";

        Object[] params = TransformUtil.beanTOArray(step);

        result = DBUtil.execute(conn, sql, params);
        return result;
    }

    @Override
    public boolean doUpdate(DishStep step) throws SQLException {
        boolean result = false;
        String sql = "update `tb_dishstep` set `dsPic` = ?, `dsContent` = ? where `cbID` = ? and `dsNO` = ?";

        Object[] values = new Object[4];
        values[0] = step.getPic();
        values[1] = step.getContent();
        values[2] = step.getID();
        values[3] = step.getNO();

        result = DBUtil.execute(conn, sql, values);
        return result;
    }

    @Override
    public boolean doDelete(long cookbookID, int stepNO) throws SQLException {
        boolean result = false;
        String sql = "delete from `tb_dishstep` where `cbID` = ? and `dsNO` = ?";

        result = DBUtil.execute(conn, sql, cookbookID, stepNO);
        return result;
    }

    @Override
    public DishStep getDishStep(long cookbookID, int stepNO)
            throws SQLException {
        DishStep result = null;
        String sql = "select * from `tb_dishstep` where `cbID` = ? and `dsNO` = ?";

        List<Object[]> all = DBUtil.query(conn, sql, cookbookID, stepNO);
        if (all.size() > 0) {
            result = new DishStep();
            result = (DishStep) TransformUtil.arrayToBean(all.get(0),
                    DishStep.class);
        }
        return result;
    }

    @Override
    public List<DishStep> getDishStep(long cookbookID) throws SQLException {
        List<DishStep> result = null;
        String sql = "select * from `tb_dishstep` where `cbID`=?";

        List<Object[]> all = DBUtil.query(conn, sql, cookbookID);
        if (all.size() > 0) {
            result = new ArrayList<DishStep>(all.size());
            for (Object[] objects : all) {
                DishStep dishStep = (DishStep) TransformUtil.arrayToBean(
                        objects, DishStep.class);
                result.add(dishStep);
            }
        }
        return result;
    }
}
